package com.dlu.safe_construction.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.dlu.safe_construction.common.ApiResult;
import com.dlu.safe_construction.common.LoginContext;
import com.dlu.safe_construction.common.utils.JWTUtils;
import com.dlu.safe_construction.common.utils.StringUtils;
import com.dlu.safe_construction.controller.BaseController;
import com.dlu.safe_construction.mapper.ManagerMapper;
import com.dlu.safe_construction.model.Manager;
import com.dlu.safe_construction.service.ManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    private String urls[] = {
            "/safe_park/manager/login.json",
            "/safe_park/manager/auth.json",
            "/safe_park/swagger**/**",
            "/safe_park/webjars/**",
            "/safe_park/v3/**",
            "/safe_park/doc.html"
    };

    @Resource
    private ManagerService managerService;

    @Resource
    private ManagerMapper managerMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        String token = getToken(request);
        String method = request.getMethod();
        String debug = request.getParameter("debug");
        if ("true".equals(debug)) {
            return true;
        }
        log.info(token);
        log.info(url);
        log.info(method);
        // 遍历需要忽略的拦截路径
        for (String item : urls) {
            if (StringUtils.partCompare(item, url)) {
                return true;
            }
        }
        ApiResult result = managerService.auth(token);
        if (!"success".equals(result.getSuccess())) {
            response.setContentType(BaseController.APPLICATION_JSON);
            response.setCharacterEncoding(BaseController.UTF_8);
            String json = JSON.toJSONString(result);
            PrintWriter out = response.getWriter();
            out.append(json);
            out.flush();
            return false;
        } else {
            Map<String, Claim> map = JWTUtils.parseToken(token);
            String uid = map.get("userId").asString();
            Manager manager = managerMapper.selectByPrimaryKey(uid);
            LoginContext.add(manager);
            return true;
        }
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("AccessToken");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("AccessToken");
        }
        return token;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // System.out.println("处理请求完成后视图渲染之前的处理操作");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // System.out.println("视图渲染之后的操作");
    }
    // ip:125.120.85.95
}
